import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {BaseComponent} from '../common/base.component';
import {UserService} from './user.service';
import {Md5} from 'ts-md5/dist/md5';
declare var $: any;
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent extends BaseComponent implements OnInit {
  password: string;
  account: string;

  constructor(private userService: UserService, private router: Router) {
    super();
  }

  ngOnInit() {
  }

  onLogin() {
    const userId = $('#userId');
    const password = $('#password');
    let msg = '';
    let msgp = '';
    if ($.trim(userId.val()) === '') {
      msg = '用户名不能为空！';

    }
    if ($.trim(password.val()) === '') {
      msgp = '密码不能为空！';

    }
    if (msg !== '') {
      this.alert.error(msg);
    }
    if (msgp !== '') {
      this.alert.error(msgp);
    }
    if ( !this.account ) {
      return;
    }
    if ( !this.password ) {
      return;
    }
    const pwdMd5 = Md5.hashStr(this.password).toString();
    this.userService.login(this.account, pwdMd5)
      .then(res => {
        if (res[0]) {
          this.router.navigate(['/buz/news']);
          this.alert.info('登陆成功');
        } else {
          this.alert.error(res[1]);
        }
      })
      .catch(error => this.alert.error('登录失败'));
  }
}
